import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { usePermissionStore } from './permission'

export const useRouterStore = defineStore('router', () => {
  // 从sessionStorage恢复路由状态，如果没有则使用空数组
  const dynamicRoutes = ref(JSON.parse(sessionStorage.getItem('dynamicRoutes')) || [])

  // 菜单列表状态
  const menuList = ref(JSON.parse(sessionStorage.getItem('menuList')) || [])

  /**
   * 保存路由到sessionStorage
   */
  const saveRoutesToStorage = () => {
    sessionStorage.setItem('dynamicRoutes', JSON.stringify(dynamicRoutes.value))
    console.log('路由配置已保存到sessionStorage')
  }

  /**
   * 设置动态路由
   * @param {Array} routes - 动态路由数组
   */
  const setDynamicRoutes = (routes) => {
    console.log('开始设置动态路由:', routes)
    const permissionStore = usePermissionStore()
    // 根据用户权限过滤路由
    const filteredRoutes = permissionStore.filterAsyncRoutes(routes)
    dynamicRoutes.value = filteredRoutes
    // 保存到sessionStorage
    saveRoutesToStorage()
    console.log('动态路由更新完成:', dynamicRoutes.value)
  }

  /**
   * 清空动态路由
   */
  const clearDynamicRoutes = () => {
    console.log('清空动态路由')
    dynamicRoutes.value = []
    sessionStorage.removeItem('dynamicRoutes')
    console.log('动态路由已清空')
  }

  /**
   * 从sessionStorage恢复路由状态
   */
  const restoreRoutes = () => {
    const savedRoutes = sessionStorage.getItem('dynamicRoutes')
    if (savedRoutes) {
      dynamicRoutes.value = JSON.parse(savedRoutes)
      console.log('已从sessionStorage恢复路由状态')
    }
  }

  // 过滤后的菜单列表
  const filteredMenus = computed(() => {
    return menuList.value.filter(item => !item.hidden)
  })

  /**
   * 根据用户权限生成路由
   * @param {Array} permissions - 用户权限列表
   */
  const generateRoutes = async (permissions) => {
    console.log('开始生成路由配置...')
    const permissionStore = usePermissionStore()
    // 导入异步路由配置
    const { asyncRoutes } = await import('../router')
    console.log('获取到异步路由配置:', asyncRoutes)
    // 设置用户权限
    permissionStore.setPermissions(permissions)
    // 过滤异步路由
    const filteredRoutes = permissionStore.filterAsyncRoutes(asyncRoutes)
    console.log('权限过滤后的路由:', filteredRoutes)
    // 更新菜单列表
    menuList.value = filteredRoutes
    sessionStorage.setItem('menuList', JSON.stringify(menuList.value))
    console.log('路由生成完成，更新菜单列表:', menuList.value)
  }

  /**
   * 清空菜单列表
   */
  const clearMenuList = () => {
    console.log('清空菜单列表')
    menuList.value = []
    sessionStorage.removeItem('menuList')
  }

  return {
    dynamicRoutes,
    menuList,
    filteredMenus,
    setDynamicRoutes,
    clearDynamicRoutes,
    restoreRoutes,
    saveRoutesToStorage,
    generateRoutes,
    clearMenuList
  }
})